/*
 * Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huawei.cloudphone.utils;

import com.huawei.cloudphone.common.CASLog;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandomSpi;
import java.util.Arrays;

public final class CasDevRandomSeed extends SecureRandomSpi {

    private static final String TAG = "CasDevRandomSeed";

    private static final String NAME_RANDOM = "/dev/random";

    @Override
    protected synchronized void engineSetSeed(byte[] seed) {
    }

    @Override
    protected synchronized void engineNextBytes(byte[] bytes) {
        byte[] seed = generateSeed(bytes.length);
        System.arraycopy(seed, 0, bytes, 0, seed.length);
        Arrays.fill(seed, (byte) 0);
    }

    @Override
    protected synchronized byte[] engineGenerateSeed(int numBytes) {
        return generateSeed(numBytes);
    }

    private byte[] generateSeed(int numBytes) {
        File seedFile = new File(NAME_RANDOM);
        try (InputStream seedIn = new FileInputStream(seedFile)) {
            byte[] bytes = new byte[numBytes];
            int len = bytes.length;
            int off = 0;
            while (len > 0) {
                int readLen = seedIn.read(bytes, off, len);
                off += readLen;
                len -= readLen;
            }
            return bytes;
        } catch (IOException e) {
            CASLog.e(TAG, "Failed to generate seed.");
        }
        return null;
    }
}